package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.api.vo.ProductSkuVo;
import com.spzx.product.api.vo.SkuPriceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author Login
 * @since 2025-07-17
 */
@Service
@Slf4j
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {
    @Autowired
    private  RedisTemplate redisTemplate;

    @Override
    public List<ProductSkuVo> getTopSale() {

        return baseMapper.selectTopSale();
    }

    @Override
    public List<ProductSkuVo> selectProductList(SkuQuery skuQuery) {

        return baseMapper.selectProductList(skuQuery);
    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {

        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getId, skuId);
        queryWrapper.select(ProductSku::getSalePrice,ProductSku::getMarketPrice);
        ProductSku productSku = baseMapper.selectOne(queryWrapper);

        SkuPriceVo skuPriceVo = new SkuPriceVo();
        skuPriceVo.setSkuId(skuId);
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());
        return skuPriceVo;

    }

    @Override
    public ProductSku getProductSkuById(Long skuId) {

        /* 移到ChannelController.item()  中了， ChannelController 是getProductSkuById 的外层
        Boolean result = redisTemplate.opsForValue().getBit("product:sku:ids", skuId);
        if (!result){
            throw new ServiceException("商品不存在");
        }*/

        //根据skuId从缓存中查询商品SKU
        String lockKey = "product:sku:lock"+skuId;
        ProductSku productSku = (ProductSku) redisTemplate.opsForValue().get(lockKey);
        //如果缓存中有，则直接返回
        if (productSku != null){
            log.info("命中缓存111");
            return productSku;
        }
        //添加分布式锁
        //使用redis的setnx设置分布式锁
        String uuid = UUID.randomUUID().toString();
        Boolean flag =redisTemplate.opsForValue().setIfAbsent("lock",uuid,2, TimeUnit.SECONDS);
        if(flag){//获取锁成功
            try {
                //再次查询缓存
                //根据skuId从缓存中查询商品SKU
                productSku = (ProductSku) redisTemplate.opsForValue().get(lockKey);
                //如果缓存中已存在，则直接返回
                if (productSku != null){
                    log.info("命中缓存222");
                    return productSku;
                }
                log.info("执行sql查询");
                //如果缓存中没有这条记录，则从数据库中查询
                productSku = baseMapper.selectById(skuId);
                if (productSku == null){
                    productSku = new ProductSku();
                }
                //再将缓存 存入redis缓存中
                long ttl = productSku == null ? 1: 10;
                //long ttl = 10;
                redisTemplate.opsForValue().set(lockKey,productSku,ttl,TimeUnit.MINUTES);
                //返回给controller层
                return productSku;
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                //锁的释放
                String script = """
                        if redis.call('get', KEYS[1]) == ARGV[1] then
                            return redis.call('del', KEYS[1])
                        else
                            return 0
                        end
                        """;
                Boolean lock = (Boolean) redisTemplate.execute(
                        new DefaultRedisScript<>(script, Boolean.class),
                        Arrays.asList("lock"),
                        uuid);
                System.out.println("result = " + lock);
            }
        }else{//获取锁失败
            try {
                Thread.sleep(100);
                return getProductSkuById(skuId);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public Map<String, Long> getSkuSpecValue(Long productId) {
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getProductId, productId);
        queryWrapper.select(ProductSku::getSkuSpec,ProductSku::getId);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);

        Map<String,Long> skuSpecValueMap = new HashMap<>();
        for(ProductSku productSku : productSkuList){
            skuSpecValueMap.put(productSku.getSkuSpec(),productSku.getId());
        }
        return skuSpecValueMap;
    }

    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {
        //根据skuid列表批量查询商品的最新价格
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ProductSku::getId,skuIdList);
        queryWrapper.select(ProductSku::getSalePrice,ProductSku::getId);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);

            List<SkuPriceVo> skuPriceVoList = productSkuList.stream()
                    .map(productSku -> {
                        SkuPriceVo skuPriceVo = new SkuPriceVo();
                        skuPriceVo.setSkuId(productSku.getId());
                        skuPriceVo.setSalePrice(productSku.getSalePrice());
                        return skuPriceVo;
                    }).toList();

        return skuPriceVoList;
    }


}
